﻿using System.Collections.Generic;
using System.ComponentModel;

namespace SyringeControl.WinForms
{
    /// <summary>
    /// Implementation of <see cref="INotifyingProperty{T}"/> storing list values.
    /// Such values can be bound to controls via complex data binding (e.g. <see cref="System.Windows.Forms.BindingSource"/>.
    /// </summary>
    /// <typeparam name="TItem">type of items in list.</typeparam>
    public class ListProperty<TItem> : PropertyBase<IList<TItem>>
    {
        /// <summary>
        /// Initializes an instance of <see cref="SimpleProperty{T}"/> class.
        /// </summary>
        /// <param name="propName">name of property that will be passed to <see cref="INotifyingProperty{T}.Changed"/> handlers.</param>
        public ListProperty(string propName)
            : base(propName)
        {
            innerValue = new BindingList<TItem>();
        }
        /// <summary>
        /// Sets property value.
        /// Raises <see cref="INotifyingProperty{T}.Changed"/>.
        /// </summary>
        /// <param name="value">value to be stored in property</param>
        /// <remarks>Actually this method don't replace inner value but clears it and fills with items from <paramref name="value"/>.
        /// It forces the <see cref="System.Windows.Forms.BindingSource"/> to be notified about change;
        /// </remarks>
        public override void Set(IList<TItem> value)
        {
            var bList = (BindingList<TItem>)innerValue;
            bList.RaiseListChangedEvents = false;
            bList.Clear();
            if (value != null)
                foreach (var item in value)
                    bList.Add(item);
            bList.RaiseListChangedEvents = true;
            bList.ResetBindings();
            InvokeChanged();
        }
    }
}
